<template>
  <div>
    <div class="search-bar">
      <van-button 
        size="small" 
        type="primary" 
        round 
        @click="goBack"
        style="margin-right: -60px; position: relative; z-index: 1;width: 60px; height: 32px; margin-top: 10px;"
      >返回</van-button>
      <van-search
        v-model="searchValue"
        placeholder="搜索商品"
        shape="round"
        background="#4fc08d"
      />
      <van-button 
        size="small" 
        type="primary" 
        round 
        @click="handleSearch"
        style="margin-left: -60px; position: relative; z-index: 1;width: 60px; height: 32px; margin-top: 10px;"
      >搜索</van-button>
    </div>
    <h1>搜索结果：{{ searchQuery }}</h1>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          v-for="item in searchResults"
          :key="item.id"
          :price="item.price"
          :title="item.name"
          :desc="item.description"
          :thumb="item.url"
        >
          <template #tags>
            <van-tag plain type="danger">{{ item.tag }}</van-tag>
          </template>
          <template #footer>
            <van-button size="small" type="primary" @click="onAddToCart(item)">加入购物车</van-button>
          </template>
        </van-card>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import {searchStore} from '@/store/searchStore'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()

const searchQuery = ref('') 
const searchResults = ref([]) 
const searchValue = ref('')
const store = searchStore()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const goBack = () => {
  router.push('/market')
}
function startFn(){
  request.get('/products')
  .then(res => {
    productList.value = res
    productList.value.forEach(item => {
      item.url = `http://8.137.113.18:8889${item.url}`
    })
  })
  .catch(err => {
    console.log(err)
  })
}

// 搜索函数
const search = () => {
  loading.value = true
  request.get('/products/filter', {
    params: { search: store.searchQuery }
  })
 .then((res) => {
    searchResults.value = res
    searchResults.value.forEach(item => {
      item.url = `http://8.137.113.18:8889${item.url}`
    })
    loading.value = false
    finished.value = false 
  })
 .catch((err) => {
    alert('搜索失败')
    loading.value = false
  })
}
if(store.searchQuery){
  search()
}else{
  startFn()
}

// 下拉刷新
const onRefresh = () => {
  setTimeout(() => {
    search()
    refreshing.value = false
  }, 1000)
}
const handleSearch = () => {
  store.setSearchQuery(searchValue.value)
  if (!store.searchQuery.trim()) {
    request.get('/products')
    .then(res => {
      searchResults.value = res
      searchResults.value.forEach(item => {
        item.url = `http://8.137.113.18:8889${item.url}`
      })
    })
    .catch(err => {
      console.log(err)
    })
    return
  }
  request.get('/products/filter', {
    params: { search: store.searchQuery }
  })
 .then((res) => {
    searchResults.value = res
    searchResults.value.forEach(item => {
      item.url = `http://8.137.113.18:8889${item.url}`
    })
    loading.value = false
    finished.value = false 
  })
 .catch((err) => {
    alert('搜索失败')
    loading.value = false
  })

  // 跳转到搜索页面
  router.push('/search')

  
}
// 加载更多（简单模拟，可根据实际分页逻辑扩展）
const onLoad = () => {
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// 加入购物车
const onAddToCart = (item) => {
  alert('添加成功')
}

</script>

<style lang="scss" scoped>
van-card {
  margin-bottom: 16px;
}
.search-bar {
  position: fixed;
  display: flex;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
:deep(.van-search){
  width: 100%;
}
:deep(.van-search__content){
  margin-right: 60px;
  margin-left: 60px;
}
</style>